package ren.nearby.home.mvp;

import com.orhanobut.logger.Logger;

import java.io.File;

import javax.inject.Inject;

import okhttp3.ResponseBody;
import ren.nearby.lib.http.HttpApi;
import ren.nearby.lib.http.progress.FileCallback;
import retrofit2.Call;


/**
 * Created by Administrator on 2018/5/14 0014.
 */

public class FragmentActAction implements FragmentContract.Action {
    FragmentContract.View mView;  // 需要抽象出来
    @Inject
    HttpApi mApi;

    @Inject
    FragmentActAction() {
//        mApi = api;
    }

    @Override
    public void takeView(FragmentContract.View view) {
        mView = view;
        Logger.e(mView == null ? " mView =  0 " : " mView = 1 ");
        Logger.e(mApi == null ? " mApi =  0 " : " mApi = 1 ");
//        if (mApi != null) {
//            mApi.dowApk();
//        }
    }
    Call<ResponseBody> responseBodyCall;
    @Override
    public void updateApk(String url,
                          String fileStoreDir,
                          String fileStoreName
    ) {
        Logger.e("进来操作了" + url);
        responseBodyCall = mApi.onlineUpload(url);
        responseBodyCall.enqueue(new FileCallback(fileStoreDir, fileStoreName) {

            @Override
            public void start(int a) {
//                mView.startUi();
            }

            @Override
            public void onSuccess(File file) {
                Logger.e("结束..");
                mView.installationApk(file);
            }

            @Override
            public void progress(long contentLength, long progress, long total) {
                mView.setProgress(contentLength, progress, total);
//                Logger.e(String.format("正在下载：(%s/%s)",
//                        getFormatSize(progress),
//                        getFormatSize(total)));
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                call.cancel();
            }
        });
    }

    public void cancel() {
        if (responseBodyCall != null && responseBodyCall.isCanceled() == false) {
            responseBodyCall.cancel();
        }
    }
    @Override
    public void dropView() {
        mView = null;
    }

    @Override
    public void test() {
        Logger.e("test");
    }
}
